package com.jackeys.piaems.filter;

import com.jackeys.piaems.annotation.PassJwt;
import com.jackeys.piaems.util.JwtUtil;
import com.jackeys.piaems.util.StatusEnumUtil;
import com.jackeys.piaems.vo.ResponseVo;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: JwtTokenInterceptor
 * @Description: jwt拦截器
 * @Author: Jackeys
 * @Date: 2021-06-19 15:00
 * @Version: 1.0
 */
@Component
public class JwtTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PassJwt annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PassJwt.class);
        } else {
            return true;
        }
        System.out.println(request.getRequestURI());
        if(request.getRequestURI().contains("ws")){
            return true;
        }
        // 如果有该注解，直接放行
        if (annotation != null) {
            return true;
        }
        // 验证token
        ResponseVo res = JwtUtil.verity();
        if (1001 == res.getCode()) {
            return true;
        }
        JSONObject json = new JSONObject();
        json.put("code",StatusEnumUtil.JWT_TOKEN_FAIl.getCode());
        json.put("msg", StatusEnumUtil.JWT_TOKEN_FAIl.getMsg());
        // 验证不通过，表示用户未登录
        response.getWriter().append(json.toString());
        return false;
    }

}

